package com.mindether.llyblog.webfilter;


import com.mindether.llyblog.dao.ViewMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


public class BlogInterceptor implements HandlerInterceptor {

    @Autowired
    private ViewMapper viewMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteAddre=request.getRemoteAddr();
        String port=request.getRemotePort()+"";
        String key=(remoteAddre+":"+port).hashCode()+"";
        String value=redisTemplate.opsForValue().get(key);
        if(value==null){
            synchronized (BlogInterceptor.class){
                value=redisTemplate.opsForValue().get(key);
                if(value==null||value.equals("")){
                    redisTemplate.opsForValue().set(key,key,6, TimeUnit.HOURS);
                    viewMapper.increaseView();
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    Logger log= LoggerFactory.getLogger(BlogInterceptor.class);
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {


    }
}
